package com.touzbi.hss.bo;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.hibernate.Session;

import com.touzbi.hss.beans.Patient;
import com.touzbi.hss.dao.AbstractPatientDAO;
import com.touzbi.hss.dao.PatientDAO;

public class SearchBO {

	private static final String QUERY_PARAM = "q";
	private static final int MIN_LENGTH = 3;
	private static final String EXCEPTION_QUERY_TOO_SHORT = "Query too short, please enter at least "
			+ MIN_LENGTH + " characters";
	private AbstractPatientDAO patientDAO;
	private String error = null;

	public SearchBO(Session session) {
		this.patientDAO = new PatientDAO(session);
	}

	public List<Patient> getQueryResult(HttpServletRequest req) {
		String query = null;
		List<Patient> patients = null;
		try {
			query = getQueryParam(req);
			patients = this.patientDAO.getQueryResult(query);
		} catch (Exception e) {
			this.error = e.getMessage();
		}

		return patients;
	}

	private String getQueryParam(HttpServletRequest req) throws Exception {
		String query = req.getParameter(QUERY_PARAM);
		if (query != null && query.length() >= MIN_LENGTH) {
			return query;
		} else {
			throw new Exception(EXCEPTION_QUERY_TOO_SHORT);
		}
	}

	public String getError() {
		return this.error;
	}

}
